const http = require('http')
const url = require('url')
const fs = require('fs')
const { createProxyMiddleware } = require('http-proxy-middleware');

function read() {
  return new Promise((resolve, reject) => {
    fs.readFile('./index.html', 'utf-8' ,(err, content) => {
      if (err) {
        reject(err.message)
      } else {
        resolve(content)
      }
    })
  })
}

http.createServer(async (req, res) => {
  let urlStr = req.url
  let { pathname } = url.parse(urlStr)

  if (/\/api/.test(pathname)) {
    const apiProxy = createProxyMiddleware('/api', { 
      target: 'https://www.xiaomiyoupin.com',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    })
    
    // http-proy-middleware 在Node.js中使用的方法
    apiProxy(req, res)
  } else {
    switch(pathname) {
      case '/index.html':
        const content = await read()
        res.write(content)
        break
  
      default:
        res.write('404, page not found.')
      }
      res.end()
    }
  }).listen(8080, () => {
  console.log('localhost:8080')
})